﻿using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.DAL;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.Devices;
using System;
using System.Linq;

namespace HamcoWcs.Service.Srm.SrmTaskParsers
{
    /// <summary>堆垛机盘点任务</summary>
    public class SrmParser_InventoryFinish : SrmParserBase
    {
        public override EnumSrmRequest RequestType => EnumSrmRequest.InventoryFinish;

        public override void Deal(SrmDto srm, SrmPlc srmPlc)
        {
            var taskEntity = GetSrmTask(srm);
            if (taskEntity == null) return;
            var loc = _wcsDbContext.WcsLocations.FirstOrDefault(x => x.WcsLocName == taskEntity.ToLoc);
            _logger.AddWcsRunLog(srm.UnitId, $"{srm.MachineName}-{srm.PortName}盘点完成,shelf:{taskEntity.ToLoc},UnitId:{srm.UnitId}");

            if (srm.UnitId.Equals("NoRead",StringComparison.OrdinalIgnoreCase))
            {
                //loc.Remark = $"盘点完成,NoRead";
                _locationService.ShelfBlock(loc.WcsLocName, "WCS", "盘点完成,NoRead");
                //loc.UnitId = "";
            }

            // 盘点时有码
            if (!string.IsNullOrEmpty(srm.UnitId))
            {
                if (loc.UnitId != srm.UnitId)
                {
                    loc.Remark = $"盘点完成,new:{srm.UnitId},old:{loc.UnitId}";
                    loc.UnitId = srm.UnitId;
                }
                if (loc.LocStatus == (int)EnumLocStatus.Empty)
                {
                    loc.LocStatus = (int)EnumLocStatus.Store;
                }
            }
            // 盘点无货
            else
            {
                loc.UnitId = "";
                if (loc.ZoneName.Contains("Z6"))
                {
                    loc.LocStatus = (int)EnumLocStatus.HandOff;
                }
                else
                {
                    loc.LocStatus = (int)EnumLocStatus.Empty;
                }
            }

            _mesCommunicateService.PalletLocStateChanged(loc);


            var machineName = loc.ZoneName.Substring(0, 8);

            //if (!(loc.LocStatus == (int)EnumLocStatus.HandOff
            //   || loc.LocStatus == (int)EnumLocStatus.TempHandOff))
            //{
            //    loc.LocStatus = string.IsNullOrWhiteSpace(srm.UnitId) ? (int)EnumLocStatus.Empty : (int)EnumLocStatus.Store;
            //}

            _wcsDbContext.SaveChanges();
            _baseTaskService.UpdateSubTaskStatus(taskEntity.Id, EnumSubTaskStatus.Finished);
        }



        private readonly IBaseTaskService _baseTaskService;

        public SrmParser_InventoryFinish(IBaseTaskService baseTaskService, ILocationService locationServce, WcsDbContext wcsDbContext, IMesCommunicateService mesCommunicateService, ILoggerService logger)
            : base(wcsDbContext, locationServce, mesCommunicateService, logger)
        {
            _baseTaskService = baseTaskService;
        }

    }
}
